<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="动态属性"></el-step>
        <el-step title="静态属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab区域 -->
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="100px" label-position='top'>
        <el-tabs v-model="activeIndex" tab-position="left" :befor-leave='beforeTabLeave' @tab-click='hangleTabClick'>
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addRuleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addRuleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addRuleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 分类列表 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader clearable v-model="addRuleForm.goods_cat" :options="cateList" :props="cascaderProps"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数(动态)" name="1">
            <!-- 动态属性复选框 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,index1) in item.attr_vals1" :key="index1">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="商品属性(静态)" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload :headers="headersObj" class="upload-demo" :action="uploadURL" :on-preview="handlePreview"
              :on-remove="handleRemove" :file-list="fileList" list-type="picture" :on-success='handleSuccess'>
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addRuleForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="butAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片的预览区域 -->
    <el-dialog title="预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewPath" alt="" class="preview">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 预览图片的存放路径
      previewPath: '',
      // 控制图片预览弹窗的显示与隐藏
      previewDialogVisible: false,
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      fileList: [],
      // 图片上传的后台API地址
      uploadURL: 'http://42.192.71.221:8889/api/private/v1/upload',
      // 静态数据列表
      onlyTabData: [],
      // 动态数据列表
      manyTabData: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      cateList: [],
      // 步骤条默认的索引 默认第一步选中
      activeIndex: '0',
      addRuleForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    // 图片上传后的预览状态
    handlePreview ({ response: { data } }) {
      this.previewPath = 'http://42.192.71.221:8889/' + data.tmp_path
      this.previewDialogVisible = true
    },
    // 删除图片临时地址  运用解构赋值
    handleRemove ({ response: { data } }) {
      const index = this.addRuleForm.pics.findIndex(item => item.pic === data.tmp_path)
      this.addRuleForm.pics.splice(index, 1)
    },
    // 添加商品
    add () {
      // 添加商品的预验证
      this.$refs.addRuleFormRef.validate(async bool => {
        if (!bool) return this.$message.error('请填写表单的必要项')

        // const form = JSON.parse(JSON.stringify(this.addRuleForm))  也可以实现深拷贝

        // 使用lodash的  _.cloneDeep方法 进行深拷贝  addRuleForm 的数据
        const form = _.cloneDeep(this.addRuleForm)
        form.goods_cat = form.goods_cat.join((','))
        console.log(form)
        // 处理动态参数
        this.manyTabData.forEach(item => {
          const newManyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addRuleForm.attrs.push(newManyInfo)
        })
        // 处理静态参数
        this.onlyTabData.forEach(item => {
          const newOnlyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addRuleForm.attrs.push(newOnlyInfo)
        })

        form.attrs = this.addRuleForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 添加成功后跳转goods页面
        this.$router.push('/goods')
      })
    },
    // 图片上传后的处理事件
    handleSuccess (response) {
      this.addRuleForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    async hangleTabClick () {
      // 动态数据列表
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        res.data.forEach(item => {
          item.attr_vals1 = item.attr_vals = item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
        console.log(this.manyTabData)
      } else if (this.activeIndex === '2') {
        // 静态数据列表
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        this.onlyTabData = res.data
        console.log(this.onlyTabData)
      }
    },
    beforeTabLeave (to, from) {
      if (from === '0' && this.addRuleForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 当选中节点变化时触发 ,返回选中的值  在分类列表数据中
    handleChange () {
      console.log(this.addRuleForm.goods_cat)
      if (this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = []
        return
      }
      console.log('do something')
    },
    // 分类列表数据
    async getParamsCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败1')
      this.cateList = res.data
    }
  },
  computed: {
    // 计算属性
    cateId () {
      if (this.addRuleForm.goods_cat.length === 3) {
        return this.addRuleForm.goods_cat[2]
      }
      return null
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getParamsCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.butAdd {
  margin-top: 15px;
}
.preview {
  width: 100%;
}
</style>
